package com.ruijie.camerax

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.util.Size
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.core.VideoCapture
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.common.util.concurrent.ListenableFuture
import com.ruijie.camerax.databinding.ActivityTakePictureBinding
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class VideoActivity : AppCompatActivity() {

    companion object {

        private const val TAG = "VideoActivity"
        private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS"
        private val REQUIRED_PERMISSIONS =
            arrayOf(
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO
            )
    }

    private lateinit var cameraProviderFuture: ListenableFuture<ProcessCameraProvider>
    private lateinit var _binding: ActivityTakePictureBinding

    private var cameraProvider: ProcessCameraProvider? = null
    private val cameraSelector = CameraSelector.Builder()
        .requireLensFacing(CameraSelector.LENS_FACING_BACK)
        .build()

    private lateinit var preview: Preview
    private val mPreviewSize = Size(1080, 1920)

    private lateinit var videoCapture: VideoCapture


    private lateinit var registerForActivityResult: ActivityResultLauncher<Array<String>>

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityTakePictureBinding.inflate(layoutInflater)
        setContentView(_binding.root)
        cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        registerForActivityResult =
            registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { results ->
                val allPermissionGranted = results.all { it.value }
                if (allPermissionGranted) {
                    startCamera()
                }
            }
        // Request camera permissions
        registerForActivityResult.launch(REQUIRED_PERMISSIONS)

        _binding.apply {
            preview = Preview.Builder()
                .setTargetResolution(mPreviewSize)
                .build()
            preview.setSurfaceProvider(previewV.surfaceProvider)

            btnStart.setOnClickListener {
                btnStart.toggle()
                if (btnStart.isChecked) {
                    startRecorder()
                } else {
                    stopRecorder()
                }
            }
        }
    }

    private fun startCamera() {
        cameraProviderFuture.addListener({
            cameraProvider = cameraProviderFuture.get()
            videoCapture = VideoCapture.Builder()
                .build()


//            val imageAnalysis = ImageAnalysis.Builder()
//                .setTargetResolution(mPreviewSize)
//                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
//                .build()
//
//            imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this),
//                { image ->
//                    val rotationDegrees = image.imageInfo.rotationDegrees
//                    // insert your code here.
//                    Log.d(TAG, "bindPreview: ${image.format} / $rotationDegrees")
//                    image.close()
//                })

            cameraProvider?.unbindAll()
            cameraProvider?.bindToLifecycle(
                this,
                cameraSelector,
                preview,
//                imageAnalysis,
                videoCapture
            )

        }, ContextCompat.getMainExecutor(this))
    }


    @SuppressLint("RestrictedApi")
    private fun startRecorder() {
        Toast.makeText(this, "开始录制", Toast.LENGTH_SHORT).show()
        val pictureFileName =
            SimpleDateFormat(FILENAME_FORMAT, Locale.CHINA).format(Date()) + ".mp4"
        val file = File(getExternalFilesDir(null), pictureFileName)
        if (!file.exists()) {
            file.createNewFile()
        }
        Log.d(TAG, "capture: ${file.absolutePath}")

        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.RECORD_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return
        }
        val outputFileOptions = VideoCapture.OutputFileOptions.Builder(file).build()
        videoCapture.startRecording(outputFileOptions,
            ContextCompat.getMainExecutor(this),
            object : VideoCapture.OnVideoSavedCallback {
                override fun onVideoSaved(outputFileResults: VideoCapture.OutputFileResults) {
                    Log.d(TAG, "onVideoSaved : ")
                }

                override fun onError(videoCaptureError: Int, message: String, cause: Throwable?) {
                    Log.d(TAG, "onError : ")
                }
            })
    }

    @SuppressLint("RestrictedApi")
    private fun stopRecorder() {
        Toast.makeText(this, "停止录制", Toast.LENGTH_SHORT).show()
        videoCapture.stopRecording()
    }


}